$(function () {
    $('#Commontop').load('../assets/public/html/PublicLoginNotLogIn.html');

    //toastr弹窗属性
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "positionClass": "toast-bottom-right",
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    }

    function errorWindows(text1, text2) {
        toastr.error(`${text2}`, `${text1}`)
    }

    function successWindows(text1, text2) {
        toastr.success(`${text2}`, `${text1}`)
    }

    //回车触发登录
    $(document).keydown(function (e) {
        const display = $('#loginPhoneCon').css('display')
        if (e.keyCode == 13) {
            if (display != 'none') {
                $('#codeBtn').click()
            } else {
                $('#passBtn').click()
            }
        }
    })

    //记住密码
    const userPhone = window.localStorage.getItem('phone')
    let userPassword = window.localStorage.getItem('password')
    userPassword = window.atob(userPassword)
    if (userPhone && userPassword) {
        $('#loginPhone2').val(userPhone);
        $('#loginPass').val(userPassword)
    }

    //防抖
    function debounce(fn, delay) {
        let t = null;
        return function () {
            t && clearTimeout(t);
            t = setTimeout(function () {
                fn();
            }, delay)
        }
    }


    $('#codeBtn').click(debounce(codeSumbit, 500))
    $('#passBtn').click(debounce(passSumbit, 500))
    $('.send_code a').click(loginSendCode)

    //切换登录状态
    function changeLogin() {
        let status = true;
        $('.change_login a').click(function () {
            if (status == 1) {
                $('#loginPhoneCon').hide()
                $('#loginPassCon').show();

            } else {
                $('#loginPassCon').hide();
                $('#loginPhoneCon').show()
            }
            status = !status;
        })
    }

    changeLogin()

    //登录成功的触发的函数
    function successLogin() {
        $('.circle').attr('class', 'circle circleAnimation')
        $('.tick').attr('class', 'tick tickAnimation')
        $('.successText').addClass('succesTextAnimation')
        $('.login_sq').hide();
        $('.agree_box').hide();
        $('.succes_login').show();
        setTimeout(() => {
            window.location.replace('index.html');
        }, 3050)
    }

    //判断手机号和验证码规则
    let vaildatorLoginCode = $('#loginPhoneCon').validate({
        debug: true,
        rules: {
            loginPhone: {
                required: true,
                minlength: 11,
                maxlength: 11,
                digits: true
            },
            loginCode: {
                required: true,
                minlength: 4,
                maxlength: 4,
                digits: true
            }
        },
        messages: {
            loginPhone: {
                required: '手机号不能为空',
                minlength: '手机号长度为11',
                maxlength: '手机号长度为11',
                digits: '格式不正确'
            },
            loginCode: {
                required: '验证码不能为空',
                maxlength: '验证码长度为4',
                digits: '格式不正确'
            }
        }
    })
    //判断手机号和密码规则
    let vaildatorLoginPass = $('#loginPassCon').validate({
        debug: true,
        rules: {
            loginPhone2: {
                required: true,
                minlength: 11,
                maxlength: 11,
                digits: true
            },
            loginPass: {
                required: true,
            }
        },
        messages: {
            loginPhone2: {
                required: '手机号不能为空',
                minlength: '手机号长度为11',
                maxlength: '手机号长度为11',
                digits: '格式不正确'
            },
            loginPass: {
                required: '密码不能为空',
            }
        }
    })

    let sendTime = 60
    //限制短信发送时间
    limitedTime = function (dom) {
        if (sendTime == 0) {
            dom.css({'pointer-events': 'auto'})
            dom.prop('disabled', false)
            dom.text('获取验证码');
            sendTime = 60
            return
        } else {
            sendTime--
            dom.css({'pointer-events': 'none'})
            dom.prop('disabled', true)
            dom.text(`${sendTime}秒后重新发送`)
        }
        setTimeout(() => {
            limitedTime(dom)
        }, 1000)
    }

    //手机验证码登录
    function codeSumbit() {
        let isChecked = $('.check').prop('checked')
        if (isChecked) {
            if (vaildatorLoginCode.form()) {
                let phoneLoginAsk = Interceptor('/phoneLogin', 'post', {
                    'phone': $('#login_phone').val(),
                    'code': $('#loginCode').val(),
                })
                let {code, message} = phoneLoginAsk;

                if (code == 304) {
                    let Authorization = phoneLoginAsk.data.token
                    let postion = phoneLoginAsk.data.position

                    sessionStorage.setItem('Authorization', Authorization)
                    sessionStorage.setItem('identity', postion)
                    successWindows(message, '')
                    successLogin();
                } else {
                    errorWindows(message, '')
                }
            }
        } else {
            errorWindows('请勾选协议', '');
        }
    }

    //手机号登陆发送验证码
    function loginSendCode() {
        let flag = false;
        const myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
        $('.errorMsg').hide()
        if ($('#login_phone').val() == '') {
            return;
        } else if (!myreg.test($('#login_phone').val())) {
            return
        } else {
            flag = true;
        }

        if (flag) {
            let loginSend = Interceptor('/send', 'post', {
                'phone': $('#login_phone').val(),
            })
            const {code, message} = loginSend;
            code != 666 ? errorWindows(message, '') : limitedTime($(this)), successWindows(message, '');

        }

    }

    //密码登录
    function passSumbit() {
        let isChecked = $('.check').prop('checked')
        if (isChecked) {
            if (vaildatorLoginPass.form()) {
                const rememberCheck = $('#rememberCheck').prop('checked');

                let passAsk = Interceptor('/passLogin', 'post',
                    {
                        'phone': $('#loginPhone2').val(),
                        'password': $('#loginPass').val(),
                    }
                )

                let {code, message} = passAsk;

                if (code == 304) {


                    let Authorization = passAsk.data.token
                    let postion = passAsk.data.position

                    sessionStorage.setItem('Authorization', Authorization)
                    sessionStorage.setItem('postion', postion);

                    if (rememberCheck) {
                        const pass = window.btoa($('#loginPass').val());
                        window.localStorage.setItem('phone', $('#loginPhone2').val())
                        window.localStorage.setItem('password', pass)
                    } else {
                        console.log(rememberCheck)
                    }
                    successWindows(message, '')
                    successLogin();
                } else {
                    errorWindows('密码登录', message)
                }
            }
        } else {
            errorWindows('请勾选协议', '');
        }
    }


})